package com.stylefeng.guns.rest.modular.auth.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.stylefeng.guns.api.user.UserApi;
import com.stylefeng.guns.core.response.ServerResponse;
import com.stylefeng.guns.rest.modular.auth.controller.dto.AuthRequest;
import com.stylefeng.guns.rest.modular.auth.controller.dto.AuthResponse;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 请求验证的
 *
 * @author fengshuonan
 * @Date 2017/8/24 14:22
 */
@RestController
public class AuthController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Reference
    // 自定义用户模块
    private UserApi userApi;

    @RequestMapping(value = "${jwt.auth-path}")
    public ServerResponse createAuthenticationToken(AuthRequest authRequest) {

        boolean validate = true;
        // 自定义登录，去除guns自带的登录校验
        int userId = userApi.login(authRequest.getUserName(), authRequest.getPassword());
        if (userId == 0) {
            validate = false;
        }

        if (validate) {
            // 生成 randomKey、token
            final String randomKey = jwtTokenUtil.getRandomKey();
            final String token = jwtTokenUtil.generateToken(String.valueOf(userId), randomKey);

            // 自定义返回值，不使用guns的返回值
            return ServerResponse.createBySuccess("登录成功", new AuthResponse(token, randomKey));
        }

        return ServerResponse.createByError("用户名或密码错误！");
    }
}
